package org.freez4.spring.configuration.metadata;

import org.freez4.spring.ioc.overview.domain.User;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.PropertiesBeanDefinitionReader;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.EncodedResource;

import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * {@link PropertiesBeanDefinitionReader} demo
 *
 * @author 阿坤同学
 * @date 2024/1/10 23:23
 */
public class PropertiesBeanDefinitionReaderDemo {

    private static final Logger logger = Logger.getLogger(PropertiesBeanDefinitionReaderDemo.class.getName());

    public static void main(String[] args) {
        // 创建 IoC 底层容器
        DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
        // 创建面向 Properties 资源的 BeanDefinitionReader 示例
        PropertiesBeanDefinitionReader beanDefinitionReader = new PropertiesBeanDefinitionReader(beanFactory);
        // Properties 资源加载默认通过 ISO-8859-1，实际存储 UTF-8
        ResourceLoader resourceLoader = new DefaultResourceLoader();
        // 通过指定的 ClassPath 获取 Resource 对象
        Resource resource = resourceLoader.getResource("classpath:/META-INF/user-bean-definitions.properties");
        // 转换成带有字符编码 EncodedResource 对象
        EncodedResource encodedResource = new EncodedResource(resource, "UTF-8");
        int beanDefinitionsCount = beanDefinitionReader.loadBeanDefinitions(encodedResource);
        logger.log(Level.INFO, () -> "已记载" + beanDefinitionsCount + "个 BeanDefinition");
        // 通过依赖查找获取 User Bean
        User user = beanFactory.getBean("user", User.class);
        logger.log(Level.INFO, () -> "properties 方式加载的User Bean" + user);
    }
}